package net.zabuchy.project.action;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
 
import net.zabuchy.activities.dao.ActivityDao;
import net.zabuchy.helper.ParamNames;
import net.zabuchy.helper.SessionHelper;
import net.zabuchy.iteration.entity.Iteration;
import net.zabuchy.project.bo.ProjectBo;
import net.zabuchy.project.entity.Project;
import net.zabuchy.user.bo.UserBo;
import net.zabuchy.user.entity.User;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
 
public class EditProjectAction extends  ActionSupport 
	implements ServletRequestAware,ServletResponseAware{ 
 
	@Autowired
    private SessionHelper sessionBean;
	@Autowired
	private ProjectBo projectBo;
	@Autowired
	private UserBo userBo;
	@Autowired
	private ActivityDao activityDao;
	    
	private HttpServletRequest request;
	private HttpServletResponse response;
	
    private static final Logger LOGGER = Logger.getLogger(CreateProjectAction.class.getName());
 
    private Integer projectId;
	private Integer customerId;
	private String title;
	private String description;
	private String status;
	private Integer defaultIterationLenght;
	private Integer nextIterationLenght;
	private Integer currentIterationNumber;
	private Date creationdate;
	private Date predictedEndDate;
    
	private Set<User> users = new HashSet<User>(0);
	private Set<Iteration> iterations = new HashSet<Iteration>(0);
	
	private List<String> usersSystem = new ArrayList<String>(0);
	private String addedUser;
	private Integer userId;
	
	private Project project;
   
	public String execute() {
		if (projectBo == null || projectId == 0) {
			return Action.ERROR;
		}
		LOGGER.debug("editForm");
		String returnInputProjectForm = request.getParameter(ParamNames.EDIT_PROJECT_FORM);
		
		boolean returnForm = (returnInputProjectForm != null ? 
				Boolean.parseBoolean(returnInputProjectForm) : false);
		
		List<User> tmp = userBo.findByCustomerId(sessionBean.getCustomerId());
		Iterator it = tmp.iterator();
		while(it.hasNext()) {
			User user = (User) it.next();
			usersSystem.add(user.getUsername());
		}
		
		if(returnForm) {
			LOGGER.debug("clear all fields and return form");
			clearFields();
			getProject(projectId);
			return Action.INPUT;
		}
		
		project = projectBo.findById(projectId);
		project.setCurrentIterationNumber(currentIterationNumber);
		project.setDefaultIterationLenght(defaultIterationLenght);
		project.setDescription(description);
		project.setNextIterationLenght(nextIterationLenght);
		project.setPredictedEndDate(predictedEndDate);
		project.setStatus(status);
		project.setTitle(title);
		
		projectBo.update(project);
		
		return Action.SUCCESS;
	}
    
	public String editProjectUsers() {
		
		LOGGER.debug("edit Project users start");
		User user = userBo.findByUsername(addedUser);
		LOGGER.debug("user.userName " + user.getUsername());
		users.add(user);
		project.setUsers(users);
		projectBo.update(project);
		
		return Action.SUCCESS;
	}
	
	public String removeUsers() {
		
		if (userBo == null) {
            return Action.ERROR;
        }
        User user = userBo.findById(userId);
        if (user == null) {
            return Action.ERROR;
        }
        
        LOGGER.debug("Remove user " + user.getUsername() + " with id " + user.getUserId() + " from project: " + projectId);
        LOGGER.debug("users: " + users.size());
        Iterator it = users.iterator();
        Set<User> temporary = new HashSet<User>(0);
        while(it.hasNext()) {
        	User tmp = (User) it.next();
        	if(user.getUserId() != tmp.getUserId()) {
        		temporary.add(tmp);
        	}
        }
        users.clear();
        users.addAll(temporary);
        LOGGER.debug("participants.size: " + users.size());
        project.setUsers(users);
        projectBo.update(project);
        
		return Action.SUCCESS;
	}
	
    private void clearFields() {
    	LOGGER.debug("TO DO");
    	this.title = null;
    	this.description = null;
    	this.status = null;
    	this.defaultIterationLenght = null;
    	this.nextIterationLenght = null;
    	this.currentIterationNumber = null;
    	this.creationdate = null;
    	this.predictedEndDate = null;
    	
    	this.users.clear();
    	this.iterations = null;
    	
    	this.addedUser = null;
    	this.userId = null;
    	
    	this.project = null;
    }
    
 
    private void getProject(Integer projectId) {
        LOGGER.debug("Get project with id = " + projectId);
        project = projectBo.findById(projectId);
        this.title = project.getTitle();
    	this.description = project.getDescription();
    	this.status = project.getStatus();
    	this.defaultIterationLenght = project.getDefaultIterationLenght();
    	this.nextIterationLenght = project.getNextIterationLenght();
    	this.currentIterationNumber = project.getCurrentIterationNumber();
    	this.predictedEndDate = project.getPredictedEndDate();
    	this.iterations = project.getIterations();
    	this.users = project.getUsers();
    }
    
    
	public List<String> getUsersSystem() {
		return usersSystem;
	}

	public void setUsersSystem(List<String> usersSystem) {
		this.usersSystem = usersSystem;
	}

	public String getAddedUser() {
		return addedUser;
	}

	public void setAddedUser(String addedUser) {
		this.addedUser = addedUser;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}
    
	public Integer getProjectId() {
		return projectId;
	}

	public void setProjectId(Integer projectId) {
		this.projectId = projectId;
	}

	public int getCustomerId() {
		return customerId;
	}

	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public ProjectBo getProjectBo() {
		return projectBo;
	}

	public void setProjectBo(ProjectBo projectBo) {
		this.projectBo = projectBo;
	}
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Integer getNextIterationLenght() {
		return nextIterationLenght;
	}

	public void setNextIterationLenght(Integer nextIterationLenght) {
		this.nextIterationLenght = nextIterationLenght;
	}

	public Integer getCurrentIterationNumber() {
		return currentIterationNumber;
	}

	public void setCurrentIterationNumber(Integer currentIterationNumber) {
		this.currentIterationNumber = currentIterationNumber;
	}

	public Date getPredictedEndDate() {
		return predictedEndDate;
	}

	public void setPredictedEndDate(Date predictedEndDate) {
		this.predictedEndDate = predictedEndDate;
	}

	public void setCustomerId(Integer customerId) {
		this.customerId = customerId;
	}

	
	public UserBo getUserBo() {
        return userBo;
    }
 
    public void setUserBo(UserBo userBo) {
        this.userBo = userBo;
    }

	public ActivityDao getActivityDao() {
		return activityDao;
	}

	public void setActivityDao(ActivityDao activityDao) {
		this.activityDao = activityDao;
	}

	/**
	 * @param users the users to set
	 */
	public void setUsers(Set<User> users) {
		this.users = users;
	}

	/**
	 * @return the users
	 */
	public Set<User> getUsers() {
		return users;
	}

	/**
	 * @param iterations the iterations to set
	 */
	public void setIterations(Set<Iteration> iterations) {
		this.iterations = iterations;
	}

	/**
	 * @return the iterations
	 */
	public Set<Iteration> getIterations() {
		return iterations;
	}

	/**
	 * @param defaultIterationLenght the defaultIterationLenght to set
	 */
	public void setDefaultIterationLenght(Integer defaultIterationLenght) {
		this.defaultIterationLenght = defaultIterationLenght;
	}

	/**
	 * @return the defaultIterationLenght
	 */
	public Integer getDefaultIterationLenght() {
		return defaultIterationLenght;
	}

	 /**
	 * @param sessionBean the sessionBean to set
	 */
	public void setSessionBean(SessionHelper sessionBean) {
		this.sessionBean = sessionBean;
	}

	/**
	 * @return the sessionBean
	 */
	public SessionHelper getSessionBean() {
		return sessionBean;
	}

	public void setServletRequest(HttpServletRequest request){
		  this.request = request;
		  }

		  public HttpServletRequest getServletRequest(){
		  return request;
		  }

		  public void setServletResponse(HttpServletResponse response){
		  this.response = response;
		  }

		  public HttpServletResponse getServletResponse(){
		  return response;
		  }

	
}